/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.modules.job.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.modules.alarm.entity.MachineEntity;
import io.renren.modules.alarm.entity.MessageEntity;
import io.renren.modules.alarm.service.GuardService;
import io.renren.modules.alarm.service.MachineService;
import io.renren.modules.alarm.service.MessageService;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 测试定时任务(演示Demo，可删除)
 * <p>
 * testTask为spring bean的名称
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component("checkTask")
public class CheckTask implements ITask {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private GuardService guardService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private MachineService machineService;

    @Override
    public void run(String params) {

        List<MachineEntity> machinelist = machineService.list(new QueryWrapper<MachineEntity>().ne("is_deleted", 1).ne("mach_status", 0));
        //System.out.println(machinelist);

        for (MachineEntity machine : machinelist) {

            Long machId = machine.getMachId();
            MessageEntity currentMsg = messageService.getCurrent(machId);

            Timestamp msgTime = currentMsg.getTime();
            Timestamp currentTime = new Timestamp(System.currentTimeMillis());

            //判断是否超时
            if (currentTime.getTime() - msgTime.getTime() > 60 * 1000 ) {
                System.out.println("获取信息超时，机器id为" + machine.getMachId());
                machine.setMachStatus(3);
                machineService.updateById(machine);
                //然后发送短信
            }

            //判断异常或正常
            else if (currentMsg.getCurrentStatus() == 2) {
                machine.setMachStatus(2);
                machineService.updateById(machine);
                //发送短信
            } else if (currentMsg.getCurrentStatus() == 1) {
                machine.setMachStatus(1);
                machineService.updateById(machine);
            }
        }

    }
}
